import { useContext } from "react";
import { BaseContext, NodeProp } from "./ContainerProvider";

export function getAnchorPosition(node: NodeProp) {
  const { width, height } = node;
  const { x, y } = node.position;
  return {
    "left-top": { cx: x, cy: y },
    top: { cx: x + width / 2, cy: y },
    "right-top": { cx: x + width, cy: y },
    left: { cx: x, cy: y + height / 2 },
    right: { cx: x + width, cy: y + height / 2 },
    "left-bottom": { cx: x, cy: y + height },
    bottom: { cx: x + width / 2, cy: y + height },
    "right-bottom": { cx: x + width, cy: y + height },
  };
}

export default function Anchors(props: NodeProp & { index: number }) {
  const { anchor, index, showAnchor } = props;
  const positionInfo = getAnchorPosition(props);
  const { events } = useContext(BaseContext);

  function handleAnchorMouseDown(
    e: React.MouseEvent,
    x: number,
    y: number,
    index: number,
    position: string
  ) {
    e.stopPropagation();
    events.on("lineStart", () => {
      return { x, y, index, position };
    });
  }

  function getAnchor() {
    if (anchor) {
      return anchor.map((i) => {
        const { cx, cy } = positionInfo[i];
        return (
          <circle
            key={i}
            cx={cx}
            cy={cy}
            r="4"
            className="anchor"
            fill="black"
            onMouseDown={(e) => handleAnchorMouseDown(e, cx, cy, index, i)}
          ></circle>
        );
      });
    }
  }
  return <g visibility={showAnchor ? "visiable" : "hidden"}>{getAnchor()}</g>;
}
